package com.shyroke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import com.shyroke.entity.User;
import com.shyroke.util.DBUtil;

public class UserDao {

	/**
	 * 根据用户名查询用户
	 * 
	 * @param userName
	 * @return User
	 */
	public User getUserByName(String userName) {
		User user = null;
		Connection conn = null;
		PreparedStatement ps = null;
		String sql = "";
		ResultSet rs = null;
		try {
			sql = "select * from user where user_name='" + userName + "'";
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			if (rs.next()) {
				user=new User();
				user.setId(rs.getInt("user_id"));
				user.setUserName(rs.getString("user_name"));
				user.setPassWord(rs.getString("user_password"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				DBUtil.close(conn, ps, rs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return user;
	}

	public Set<String> getRolesByName(String userName) {
		Set<String> roles = new HashSet<String>();

		Connection conn = null;
		PreparedStatement ps = null;
		StringBuffer sb = new StringBuffer();
		ResultSet rs = null;
		try {
			sb.append("select role_name from role where role_id in");
			sb.append("(");
			sb.append("select role_id from user_role where user_id in(");
			sb.append("select user_id from user where user_name='" + userName + "')");
			sb.append(")");
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sb.toString());
			rs = ps.executeQuery();

			while (rs.next()) {
				roles.add(rs.getString("role_name"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				DBUtil.close(conn, ps, rs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return roles;
	}

	public Set<String> getPermissionsByName(String userName) {
		Set<String> perms = new HashSet<String>();

		Connection conn = null;
		PreparedStatement ps = null;
		StringBuffer sb = new StringBuffer();
		ResultSet rs = null;
		try {
			sb.append("select permission_name from permission where permission_id in(");
			sb.append("select permission_id from permission_role where role_id in");
			sb.append("(");
			sb.append("select role_id from user_role where user_id in");
			sb.append("	(");
			sb.append("		select user_id from user where user_name='"+userName+"'");
			sb.append("		)");
			sb.append("		)");
			sb.append("		)");
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sb.toString());
			rs = ps.executeQuery();

			while (rs.next()) {
				perms.add(rs.getString("permission_name"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				DBUtil.close(conn, ps, rs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return perms;
	}

}
